<?php
final class XConfig{
	private static $instance = null;
	private $contents = array();
	private $extensions = array();
	private $hasExtensions = false;
	private $dir = '';
	
	private function __construct() {
		$this->dir = PROJECT_ROOT.DIRECTORY_SEPARATOR.'config';
	}
	
	/** 
	 * @return XConfig
	 */		
	public static function singleton() {
		if (!self::$instance) {
			self::$instance = new self;
		}
		return self::$instance;
	}
	
	public function load() {
		if(!is_dir($this->dir)){
			return;
		}
		$this->_loadConfigMetaData();
		$this->_loadDir($this->dir);
	}
	
	/** 
	 * @return mixed
	 */	
	public function get($key){
		return x_array_get($this->contents, $key);
	}
	
	/** 
	 * @return array
	 */	
	public function getAll(){
		return $this->contents;
	}
	
	private function _loadFile($file){
		if($this->hasExtensions){
			$loader = new XBasicConfigLoader();
			$result = $loader->loadExtensions($file, $this->extensions);
			if($result){
				$this->_add($result);	
				return;
			}
		}
		$loader = new XBasicConfigLoader();
		$this->_add($loader->load($file));		
	}
	
	private function _loadDir($dir){
		$root = new XFile($dir);
		$files = $root->listFiles();
		foreach($files as $file){
			if($file->isDirectory()){
				$this->_loadDir($file->getPath());
			}elseif($file->isFile()){
				$this->_loadFile($file->getPath());
			}
		}
	}
	
	private function _set($key, $value){
		x_array_set($this->contents, $key, $value, true);
	}
	
	private function _add($array){
		if(!is_array($array)){
			return;
		}
		foreach($array as $key => $value){
			$this->_set($key, $value);
		}
	}
	
	private function _loadConfigMetaData(){
		foreach(array(
				'config.php',
				'config.yaml',
				'config.ini',
				'config.xml',
			) as $file){
			$path = $this->dir.'/'.$file;
			if(file_exists($path)){				
				$this->_loadFile($path);
			}
		}
		$this->extensions = $this->get('project.config.extensions');
		$this->hasExtensions = is_array($this->extensions) && count($this->extensions) > 0;
	}
}
?>